<template>
  <div style="width: 100%" :class="props.border ? 'tab-fields-config' : ''">
    <div v-for="(tab, index) in tabs" :key="index" class="config-item">
      <el-input
        v-model="tab.tab_name"
        placeholder="请输入选项卡名称"
        style="width: 30%; margin-right: 10px"
      />

      <el-select
        v-model="tab.tab_fields"
        clearable
        multiple
        filterable
        placeholder="请选择字段"
        style="width: 70%; margin-right: 10px"
      >
        <el-option
          v-for="field in fieldsList"
          :key="field.value"
          :label="field.label"
          :value="field.value"
        />
      </el-select>

      <el-button
        v-if="tabs.length > 1"
        type="danger"
        icon="Close"
        circle
        @click="removeTab(index)"
      />
    </div>

    <div class="action-buttons">
      <el-button type="primary" @click="addTab">添加选项卡</el-button>
      <el-button @click="clearTabs">清空配置</el-button>
    </div>
  </div>
</template>

<script setup>
/**
 * 这是一个用于设置不同的字段，设置于不同的选项卡中的组件
 */
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  fieldsList: {
    type: Array,
    default: () => [
      { label: '姓名', value: 'name' },
      { label: '年龄', value: 'age' },
      { label: '性别', value: 'gender' },
    ],
  },
  border: {
    type: Boolean,
    default: true,
  },
});

const emit = defineEmits(['update:modelValue']);

// 初始化默认项
const initItem = () => ({
  tab_name: '',
  tab_fields: [],
});

// 数据存储
const tabs = ref(
  props.modelValue.length ? [...props.modelValue] : [initItem()],
);

// 同步数据到父组件
watch(
  tabs,
  (newVal) => {
    emit('update:modelValue', newVal);
  },
  { deep: true },
);

// 添加新选项卡
const addTab = () => {
  tabs.value.push(initItem());
};

// 删除选项卡
const removeTab = (index) => {
  tabs.value.splice(index, 1);
};

// 清空配置
const clearTabs = () => {
  tabs.value = [initItem()];
};
</script>

<style scoped>
.tab-fields-config {
  border: 1px solid #ebeef5;
  padding: 15px;
  border-radius: 4px;
}

.config-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.action-buttons {
  margin-top: 15px;
}
</style>
